package xyz.longicorn.driver.service;

import cn.hutool.core.lang.UUID;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.longicorn.driver.config.RabbitConfig;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class RabbitMQService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public boolean sendMessage(String message) {
        try {
            String msgId = UUID.fastUUID().toString();
            String sendTime = sdf.format(new Date());
            Map<String, Object> map = new HashMap<>();
            map.put("id", msgId);
            map.put("sendTime", sendTime);
            map.put("message", message);

            // 发送
            rabbitTemplate.convertAndSend(
                    RabbitConfig.RABBITMQ_DEFAULT_DIRECT_EXCHANGE, // 接收消息的交换机
                    RabbitConfig.RABBITMQ_DEFAULT_DIRECT_ROUTING, // 发送消息的路由
                    map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
